package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.enums.PaymentWay;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 李旭
 * @date 2022/1/23 10:23
 * @Description:
 */
@Service
public class AlipayServiceImpl implements AlipayService {


    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private AlipayClient alipayClient;
    //支付宝支付的实现方法
    @Override
    public String submit(Long orderId) {
        //1:准备支付信息表的数据
        PaymentInfo paymentInfo = paymentInfoService.
                savePaymentInfo(orderId, PaymentType.ALIPAY);

        //2:调用 遥远的机房中的支付宝服务器
        //统一收单下单并支付页面接口
        // alipay.trade.page.pay
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(AlipayConfig.return_payment_url);//同步回调 给消费者看的
        request.setNotifyUrl(AlipayConfig.notify_payment_url);//异步回调  给商家看的
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", paymentInfo.getOutTradeNo());//商户订单号
        bizContent.put("total_amount", paymentInfo.getTotalAmount());
        bizContent.put("subject", paymentInfo.getSubject());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getBody());//返回页面
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }


    //.......
}
